/*
 * @desc 封装网络请求
 * *************useage**************
 * await request.get(url, { params });
 * await request.post(url, { data });
 * *********************************
 * @Author: zhangshaohui
 * @Date: 2021-07-27 11:01:14
 * @Last Modified by: zhangshaohui
 * @Last Modified time: 2021-07-27 11:08:13
 */
import Taro from '@tarojs/taro';
import { extend } from 'umi-request';
import { httpCode } from './resCode';
import errorHandler from './errorHandler';
import { HttpError } from './errorType';
import { Toast } from 'antd-mobile';

const request = extend({
  timeout: 15000,
  credentials: 'include',
  errorHandler,
  prefix: '/cdss/follow-pro',
});

// 拦截器
request.interceptors.request.use((url, options) => {
  let headers = {
    'Content-Type': 'application/json; charset=utf-8',
  };
  // 设置contentType
  if (url.indexOf('/official/upload') !== -1) {
    delete headers['Content-Type'];
  }
  return { url, options: { ...options, headers } };
});
request.interceptors.response.use(async response => {
  // 正常httpcode状态
  if (response.status === httpCode.SUCCESS) {
    const res = await response.clone().json();
    if (res.code !== 0) {
      Toast.show({
        icon: 'fail',
        content: `${res.message}`,
      });
    }
    return res;
  }
  // 判断没有登录跳转到登录页面
  else if (response.status === httpCode.NOTLOGIN) {
    Taro.reLaunch({
      url: `/follow-up-wx-patient/login?channel=${Taro.getStorageSync(
        'channel',
      )}`,
    });
  }
  // 统一的错误提示
  else {
    throw new HttpError('', response.status);
  }
});
export default request;
